package com.ruoyi.framework.mqtt.handler;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.project.instrument.domain.InsInstrument;
import com.ruoyi.project.instrument.domain.InsInstrumentUseStatistics;
import com.ruoyi.project.instrument.service.IInsInstrumentService;
import com.ruoyi.project.instrument.service.IInsInstrumentUseStatisticsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * @author Taney
 */
@Component
public abstract class AbstractHandler implements MessageHandler {
    protected Logger logger = LoggerFactory.getLogger(getClass());

    protected static final int ALARM = 1;
    protected static final int MAINTAIN = 2;
    protected static final int REAGENT_USE = 3;
    protected static final int ITEM_TEST = 4;

    @Autowired
    IInsInstrumentService insInstrumentService;
    @Autowired
    IInsInstrumentUseStatisticsService insInstrumentUseStatisticsService;

    protected boolean matches(String topic, String currentTopic) {
        boolean matches = currentTopic.contains(topic);
        if (matches) {
            logger.debug("{} message arrived", topic);
        }
        return matches;
    }

    protected boolean isJson(String msg) {
        return msg != null && JSONUtil.isJson(msg);
    }

    protected ClientInfo getClientInfo(String topic) {
        return new ClientInfo(topic).invoke();
    }

    protected class ClientInfo {
        private String topic;
        private String product;
        private String deviceId;

        public ClientInfo(String topic) {
            this.topic = topic;
        }

        public String getProduct() {
            return product;
        }

        public String getDeviceId() {
            return deviceId;
        }

        public ClientInfo invoke() {
            product = topic.split("/")[2];
            deviceId = topic.split("/")[3];
            return this;
        }
    }

    /**
     * 触发重新统计
     *
     * @param deviceId
     * @param statisticsType
     */
    protected void reStatistics(String deviceId, int statisticsType, Integer count) {
        count = count == null ? 1 : count;
        //查询设备ID
        QueryWrapper<InsInstrument> insInstrumentQueryWrapper = new QueryWrapper<>();
        insInstrumentQueryWrapper.eq("name", deviceId);
        List<InsInstrument> instruments = insInstrumentService.list(insInstrumentQueryWrapper);
        for (InsInstrument instrument : instruments) {
            if (instrument != null) {
                QueryWrapper<InsInstrumentUseStatistics> useStatisticsQueryWrapper = new QueryWrapper<>();
                Date now = new Date();
                //获取今日的时间区间
                DateTime beginTime = DateUtil.beginOfDay(now);
                DateTime endTime = DateUtil.endOfDay(now);
                useStatisticsQueryWrapper.eq("instrument_id", instrument.getId());
                InsInstrumentUseStatistics instrumentUseStatistics = insInstrumentUseStatisticsService.getOne(useStatisticsQueryWrapper);
                //今日记录次数+1
                if (instrumentUseStatistics != null) {
                    QueryWrapper<InsInstrumentUseStatistics> clone = useStatisticsQueryWrapper.clone();
                    clone.between("last_update_time", beginTime, endTime);
                    InsInstrumentUseStatistics record = insInstrumentUseStatisticsService.getOne(useStatisticsQueryWrapper);
                    setCount(statisticsType, instrumentUseStatistics, instrumentUseStatistics.getAlarmCount() + count, instrumentUseStatistics.getMaintainCount() + count, instrumentUseStatistics.getReagentUseCount() + count, instrumentUseStatistics.getItemTestCount() + count);
                    if (record == null) {
                        instrumentUseStatistics.setLastUpdateTime(now);
                    }
                    insInstrumentUseStatisticsService.update(instrumentUseStatistics, useStatisticsQueryWrapper);
                } else {
                    instrumentUseStatistics = new InsInstrumentUseStatistics();
                    setCount(statisticsType, instrumentUseStatistics, count, count, count, count);
                    instrumentUseStatistics.setInstrumentId(instrument.getId());
                    instrumentUseStatistics.setLastUpdateTime(now);
                    insInstrumentUseStatisticsService.save(instrumentUseStatistics);
                }
            }
        }
    }

    private void setCount(int statisticsType, InsInstrumentUseStatistics instrumentUseStatistics, int alarmCount, int maintainCount, int reagentUseCount, int itemTestCount) {
        switch (statisticsType) {
            case ALARM:
                instrumentUseStatistics.setAlarmCount(alarmCount);
                break;
            case MAINTAIN:
                instrumentUseStatistics.setMaintainCount(maintainCount);
                break;
            case REAGENT_USE:
                instrumentUseStatistics.setReagentUseCount(reagentUseCount);
                break;
            case ITEM_TEST:
                instrumentUseStatistics.setItemTestCount(itemTestCount);
                break;
            default:
        }
    }
}
